package com.project.template.service.impl;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.template.dto.SysUserDTO;
import com.project.template.entity.Banner;
import com.project.template.entity.Exam;
import com.project.template.entity.Score;
import com.project.template.entity.SysUser;
import com.project.template.exception.CustomException;
import com.project.template.mapper.ExamMapper;
import com.project.template.service.ExamService;
import com.project.template.service.ScoreService;
import com.project.template.service.SysUserService;
import com.project.template.utils.UserThreadLocal;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDate;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.stream.Collectors;

/**
 * <p>
 * 考试表 服务实现类
 * </p>
 *

 */
@Service
public class ExamServiceImpl extends ServiceImpl<ExamMapper, Exam> implements ExamService {

    @Resource
    private ScoreService scoreService;
    @Resource
    private ExamMapper examMapper; // 注入 examMapper

    @Resource
    private SysUserService userService;

    @Override
    public boolean save(Exam entity) {
        check(entity);
        return super.save(entity);
    }

    @Override
    public boolean updateById(Exam entity) {
        check(entity);
        return super.updateById(entity);
    }

    private void check(Exam entity) {
//        LambdaQueryWrapper<Exam> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Exam::getName, entity.getName());
//        wrapper.ne(entity.getId() != null, Exam::getId, entity.getId());
//        if (count(wrapper) > 0) {
//            throw new CustomException("名称重复");
//        }
    }


    @Override
    public boolean removeByIds(Collection<?> list) {
        List<Integer> integerList = (List<Integer>) list;
//        list(new LambdaQueryWrapper<Exam>().in(Exam::getId, integerList)).forEach(test -> {
//            if (true) {
//                throw new CustomException("删除失败");
//            }
//        });
        return super.removeByIds(integerList);
    }
//在线考试页面只显示进行中的考试
    @Override
    public Page<Exam> pageAll(Map<String, Object> query, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Exam> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Exam::getId);

        if (ObjectUtils.isNotEmpty(query.get("name"))) {
            wrapper.like(Exam::getName, query.get("name"));
        }

        SysUserDTO currentUser = UserThreadLocal.getCurrentUser(); // 学生查老师布置的作业
        if ("TEACHER".equals(currentUser.getRoleType())) {
            wrapper.eq(Exam::getUserId, currentUser.getId());
        }

        // 获取当前时间戳（秒级）
        long nowSeconds = System.currentTimeMillis() / 1000;

        // 将时间戳转换为LocalDateTime对象
        LocalDateTime nowDateTime = LocalDateTime.ofInstant(Instant.ofEpochSecond(nowSeconds), ZoneId.systemDefault());

        LocalDateTime nowDateTimePlus8Hours = nowDateTime.plusHours(8);

        // 使用加上8小时后的时间进行比较
        wrapper.apply("start_time <= {0} AND end_time >= {0}", nowDateTimePlus8Hours);
        System.out.println("Current timestamp for comparison: " + nowDateTimePlus8Hours);

        Page<Exam> page = page(new Page<>(pageNum, pageSize), wrapper);
        List<Exam> list = page.getRecords();

        // 查找用户id 和作业id相同的数据
        list.forEach(item -> {
            SysUser user = userService.getById(item.getUserId());
            if (user != null) {
                item.setUser(user.getUsername());
            }
            LambdaQueryWrapper<Score> scoreLambdaQueryWrapper = new LambdaQueryWrapper<>();
            scoreLambdaQueryWrapper.eq(Score::getUserId, currentUser.getId())
                    .eq(Score::getExamId, item.getId())
                    .last("limit 1");
            Score one = scoreService.getOne(scoreLambdaQueryWrapper);
            if (one != null) {
                item.setIsExam("已考试");
            } else {
                item.setIsExam("立即考试");
            }
        });
        page.setRecords(list);
        return page;
    }

    @Override
    public void shuffleExamQuestions(Exam exam) {
        try {
            if (exam == null) {
                throw new IllegalArgumentException("Exam object cannot be null");
            }
            if (exam.getQuestion() == null) {
                throw new IllegalArgumentException("Question string cannot be null");
            }

            // 解析题目ID字符串为整数列表
            List<Integer> questionIds = parseQuestionIds(exam.getQuestion());

            // 应用Fisher-Yates Shuffle算法随机化列表
            Collections.shuffle(questionIds);

            // 将随机化后的列表转换回字符串并更新Exam对象
            exam.setQuestion(serializeQuestionIds(questionIds));

            // 更新数据库中的题目顺序
            examMapper.updateExamQuestions(exam);
        } catch (Exception e) {
            // 记录日志
//            logger.error("Error shuffling exam questions: ", e);
            throw e;
        }
    }

    private List<Integer> parseQuestionIds(String questionIds) {
        if (questionIds == null || questionIds.isEmpty()) {
            throw new IllegalArgumentException("Question string cannot be empty");
        }
        try {
            return Arrays.stream(questionIds.split(","))
                    .map(String::trim)
                    .map(Integer::valueOf)
                    .collect(Collectors.toList());
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid question IDs: " + questionIds, e);
        }
    }

    private String serializeQuestionIds(List<Integer> questionIdList) {
        return questionIdList.stream()
                .map(Object::toString)
                .collect(Collectors.joining(","));
    }


    @Override
    public Page<Exam> page(Map<String, Object> query, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<Exam> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Exam::getId);

        if (ObjectUtils.isNotEmpty(query.get("name"))) {
            wrapper.like(Exam::getName, query.get("name"));
        }

        SysUserDTO currentUser = UserThreadLocal.getCurrentUser();        // 学生查老师布置的作业
        if ("TEACHER".equals(currentUser.getRoleType())) {
            wrapper.eq(Exam::getUserId, currentUser.getId());
        }
        Page<Exam> page = page(new Page<>(pageNum, pageSize), wrapper);
        List<Exam> list = page.getRecords();
        //查找用户id 和作业id相同的数据
        list.forEach(item->{
            SysUser user = userService.getById(item.getUserId());
            if(user!=null){
                item.setUser(user.getUsername());
            }
            LambdaQueryWrapper<Score> scoreLambdaQueryWrapper = new LambdaQueryWrapper<>();
            scoreLambdaQueryWrapper.eq(Score::getUserId,currentUser.getId())
                    .eq(Score::getExamId,item.getId())
                    .last("limit 1");
            Score one = scoreService.getOne(scoreLambdaQueryWrapper);
            if(one!=null){
                item.setIsExam("已考试");
            }else{
                item.setIsExam("立即考试");
            }
        });
        page.setRecords(list);
        return page;
    }

}